﻿/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine.display.renderers {
	
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	import stencil.core.errors.RequiredPropertyError;
	import stencil.core.errors.NotImplementedMethodError;
	import stencil.core.engine.events.TileRenderEvent;
	import stencil.core.engine.display.IDisplayObject;
	import stencil.core.engine.display.IFillStyle;
	import stencil.core.engine.display.ILineStyle;
	import stencil.core.engine.display.ITileRenderer;
	import stencil.core.engine.TileSettings;
	import stencil.core.engine.IGrid;
	import stencil.core.engine.ITileSection;
	import stencil.core.engine.MapNode;
	import stencil.core.engine.Position;	
	import stencil.core.engine.Box;
	
	/**
	 * Base implementation of ITileRenderer interface.
	 * 
	 * @author Max Zhuravkov
	 */
	public class TileRendererBase extends EventDispatcher implements ITileRenderer {
	
		private var _tileSettings:TileSettings;
		
		private var _sections:Array = [];
		
		private var _sectionsToDraw:Array = [];
		
		private var _sectionsMap:Dictionary = new Dictionary();
		
		private var _displayObjects:Dictionary = new Dictionary();
		
		private var _grid:IGrid;
		
		private var _renderCount:int = 3;
		
		private var _lineStyle:ILineStyle;
		
		private var _fillStyle:IFillStyle;
		
		private var _showGrid:Boolean;
		
		private var flagRedrawTiles:Boolean = false;
		
		private var flagRedrawSection:Boolean = false;
				
		private var _sectionsToRedraw:Array = [];
		
		private var _newSections:Array;
		
		protected var flagShowGridChanged:Boolean = false;
		
		//----------------------------------------------------------------
		// Constructor
		//----------------------------------------------------------------
		
		public function TileRendererBase() {
		}
		
		//------------------------------------------------------------------------------------------------
		// Public properties
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function get tiles():Array {
			var tiles:Array = new Array();
			
			for each(var tile:IDisplayObject in this._displayObjects) {
				tiles.push(tile);
			}
			
			return tiles;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function set renderCount(value:int):void {
			if (this._renderCount == value) {
				return;
			}
			this._renderCount = value;
		}
		
		public final function get renderCount():int {
			return this._renderCount;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function set tileSettings(value:TileSettings):void {
			this._tileSettings = value;
		}
		
		public final function get tileSettings():TileSettings {
			return this._tileSettings;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function set grid(value:IGrid):void {
			this._grid = value;
		}
		
		public final function get grid():IGrid {
			return this._grid;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function set showGrid(value:Boolean):void {
			if (this._showGrid == value) {
				return;
			}
			this._showGrid = value;
			this.flagShowGridChanged = true;
		}
		
		public final function get showGrid():Boolean {
			return this._showGrid;
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function gridStyle(lineStyle:ILineStyle = null, fillStyle:IFillStyle = null):void {
			this._lineStyle = lineStyle;
			this._fillStyle = fillStyle;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function getDisplayObject(section:ITileSection):IDisplayObject  {
			return this.displayObjects[section.id]
		}
		
		/**
		 * @inheritDoc
		 */
		public final function redrawTiles(section:ITileSection):void {
			for each(var s:ITileSection in this._sectionsToRedraw){
				if (s.id == section.id) {
					return;
				}
			}
			this._sectionsToRedraw.push(section);
			this.flagRedrawSection = true;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function clear():void {
			if(this._newSections.length > 0){
				this._newSections = [];
			}
			while(this._sectionsToDraw.length > 0){
				this._sectionsToDraw.shift()
			}
			while (this._sectionsToRedraw.length > 0) {
				this._sectionsToRedraw.shift();
			}
			
			this.flagRedrawTiles = true;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function draw(sections:Array):void {
			if (sections == null) {
				throw new Error("sections should be not null.");
			}
			this._newSections = sections.concat();
			this.flagRedrawTiles = true;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function render():void {
			
			if (!this.grid) {
				throw new RequiredPropertyError(this, "grid");
			}
			
			if (!this.tileSettings) {
				throw new RequiredPropertyError(this, "tileSettings");
			}
			
			if (!this.flagRedrawTiles && !this.flagRedrawSection) {
				return;
			}
			
			this.beforeRender();
			
			if (!this._sectionsToDraw.length) {
				this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_BEGIN_RENDER));
			}
			
			if (this.flagRedrawSection && this._sections.length) {
				this.checkSectionsMarkedAsRedrawn();
			}
			
			if(this.flagRedrawTiles){
				if (!this._sections.length) {
					this._sectionsToDraw = this._newSections.concat();
				}else {
					this.removeSections(this._sections, this._newSections);
					this.removeSections(this._sectionsToDraw, this._newSections);
					
					for each(var newSection:ITileSection in this._newSections) {
						
						var isNew:Boolean = true;
						var s:ITileSection = null;
						for each(var section:ITileSection in this._sections) {
							if (section.id == newSection.id) {
								isNew = false;
								s = section;
								break;
							}
						}
						
						if (!isNew) {
							this.updateSection(newSection, false);
						}else {
							this.updateDrawQueue(newSection);
						}
					}
				}
			}
			
			this.renderFurther();
			this.flagRedrawSection = false;
			this.flagShowGridChanged = false;
			
			if (!this._sectionsToDraw.length) {
				this.flagRedrawTiles = false;
				this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_COMPLETE_RENDER));
			}
		}
		
		public function dispose():void {
			this.clear();
			
			this._sections = null;
			this._grid = null;
			this._tileSettings = null;
			this._displayObjects = null;
		}
		
		//------------------------------------------------------------------------------------------------
		// Private methods
		//------------------------------------------------------------------------------------------------
		
		private function checkSectionsMarkedAsRedrawn():void {
			if (this._newSections) {
				for (; this._sectionsToRedraw.length > 0; ) {
					var sectionToRedraw:ITileSection = this._sectionsToRedraw.shift();
					var found:Boolean = false;
					
					for each(var newSection:ITileSection in this._newSections) {
						if (sectionToRedraw.id == newSection.id) {
							found = true;
							break;
						}
					}
					
					this.updateSection(sectionToRedraw, true);
				}
			}
		}
		
		private function drawSection(section:ITileSection):void {
			var o:IDisplayObject = this.createDisplayObject(section);
			
			this.drawTileSection(section, o);
			this.displayObjects[section.id] = o;
			
			this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_SECTION_CREATE, section));
		}
		
		private function updateSection(section:ITileSection, redrawFlag:Boolean):void {
			var o:IDisplayObject = this.getDisplayObject(section);
			
			this.updateTileSection(section, o, redrawFlag);
			
			this.displayObjects[section.id] = o;
			
			if(!redrawFlag){
				this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_SECTION_UPDATE, section));
			}else {
				this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_SECTION_REDRAW, section));
			}
		}
		
		private function updateDrawQueue(section:ITileSection):void {
			var length:int = this._sectionsToDraw.length;
			var addToQueue:Boolean = true;
			for (var i:int = 0; i < length; i ++ ) {
				var s:ITileSection = this._sectionsToDraw[i];
				if (s.id == section.id) {
					addToQueue = false;
					break;
				}
			}
			
			if (addToQueue) {
				this._sectionsToDraw.push(section);
			}
		}
		
		private function removeSections(sections:Array, newSections:Array):void {
			
			var count:int = sections.length;
			for (var i:int = 0; i < count; i ++ ) {
				var exists:Boolean = false;
				var section:ITileSection = sections[i];
				
				for each(var newSection:ITileSection in newSections) {
					if(section.id == newSection.id){
						exists = true;
						break;
					}
				}
				if (!exists) {
					sections.splice(i, 1);
					
					this.removeSection(section);
					
					if(i > 0){
						i --;
					}
					count --;
				}
			}
		}
		
		
		private function removeSection(section:ITileSection):void {
			var o:IDisplayObject = this.getDisplayObject(section);
			
			if (o) {
				
				this.dispatchEvent(new TileRenderEvent(TileRenderEvent.STN_SECTION_REMOVE, section));
				
				this.releaseTiles(o, section);
				
				delete this.displayObjects[section.id];
			}
		}
		
		private function renderFurther():void {
			var length:int = this._sectionsToDraw.length;
			var limit:int = this.renderCount < 0 || this.renderCount > length  ? length : this.renderCount;
			var rendered:Boolean = false;
			
			for (var i:int = 0; this._sectionsToDraw.length > 0 || i < limit ; i ++ ) {
				var section:ITileSection = this._sectionsToDraw.shift() as ITileSection;
				if (!section) {
					break;
				}
				this._sections.push(section);
				this.drawSection(section);
			}
		}
		
		//------------------------------------------------------------------------------------------------
		// Protected properties
		//------------------------------------------------------------------------------------------------
		
		protected final function get displayObjects():Dictionary {
			return this._displayObjects;
		}
		
		protected final function get lineStyle():ILineStyle {
			return this._lineStyle;
		}
		
		protected final function get fillStyle():IFillStyle {
			return this._fillStyle;
		}
		
		protected final function get sections():Array {
			return this._sections;
		}
		
		//------------------------------------------------------------------------------------------------
		// Protected methods
		//------------------------------------------------------------------------------------------------
		
		protected function beforeRender():void {
			
		}
		
		/**
		 * Releases resources allocated by the tile section.
		 * 
		 * @param	o	the display object.
		 * @param	section	yje tile section.
		 */
		protected function releaseTiles(o:IDisplayObject, section:ITileSection):void {
			o.dispose();
		}
		
		/**
		 * Creates display object for the given tile section.
		 * 
		 * @param	section	the tile section.
		 * 
		 * @return
		 */
		protected function createDisplayObject(section:ITileSection):IDisplayObject {
			throw new NotImplementedMethodError("createDisplayObject")
			
			return null;
		}
		
		/**
		 * Draws the given tile section. 
		 * 
		 * @param	section	the tile section.
		 * @param	destination	the display object to draw tiles onto.
		 */
		protected function drawTileSection(section:ITileSection, destination:IDisplayObject):void {
			throw new NotImplementedMethodError("drawTileSection");
		}
		
		/**
		 * Updates the given tile section.
		 * 
		 * @param	section	the tile section.
		 * @param	displayObject	the display object representing the given tile section.
		 * @param	redrawFlag	whether tiles should be redrawn or not.
		 */
		protected function updateTileSection(section:ITileSection, oldTiles:IDisplayObject, redrawFlag:Boolean):void {
			throw new NotImplementedMethodError("updateTileSection");
		}
	}
	
}
